import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'dart:io';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';

class DBHelper {
  static Database? _db;

  static Future<Database> get database async {
    if (_db != null) return _db!;
    _db = await _initDB();
    return _db!;
  }

  static Future<Database> _initDB() async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, 'huxi_system.db');
    final factory = (Platform.isWindows || Platform.isLinux) ? databaseFactoryFfi : databaseFactory;
    return await factory.openDatabase(
      path,
      options: OpenDatabaseOptions(
        version: 1,
        onCreate: (db, version) async {
          // 用户表
          await db.execute('''
            CREATE TABLE user (
              id TEXT PRIMARY KEY,
              name TEXT,
              profession TEXT,
              stage TEXT,
              progress TEXT,
              favorites TEXT,
              settings TEXT
            )
          ''');
          // 理论知识表
          await db.execute('''
            CREATE TABLE theory (
              id TEXT PRIMARY KEY,
              jing TEXT,
              summary TEXT,
              pathogenesis TEXT,
              symptoms TEXT,
              therapy TEXT,
              formula TEXT,
              isFavorite INTEGER,
              hasNote INTEGER,
              isKey INTEGER,
              progress REAL DEFAULT 0,
              lastStudyTime TEXT,
              note TEXT
            )
          ''');
          // 医案表
          await db.execute('''
            CREATE TABLE case_record (
              id TEXT PRIMARY KEY,
              title TEXT,
              source TEXT,
              date TEXT,
              author TEXT,
              patient_info TEXT,
              chief_complaint TEXT,
              history TEXT,
              symptoms TEXT,
              signs TEXT,
              analysis TEXT,
              prescription TEXT,
              effect TEXT,
              tags TEXT
            )
          ''');
          // 处方表
          await db.execute('''
            CREATE TABLE prescription (
              id TEXT PRIMARY KEY,
              name TEXT,
              source TEXT,
              category TEXT,
              composition TEXT,
              dosage TEXT,
              usage TEXT,
              indication TEXT,
              caution TEXT
            )
          ''');
          // 练习表
          await db.execute('''
            CREATE TABLE practice (
              id TEXT PRIMARY KEY,
              userId TEXT,
              type TEXT, -- 基础/进阶/临床
              difficulty TEXT, -- 初级/中级/高级
              question TEXT,
              answer TEXT,
              userAnswer TEXT,
              score INTEGER,
              createdAt TEXT,
              tags TEXT,
              status TEXT, -- 正确/错误/未做
              analysis TEXT
            )
          ''');
        },
      ),
    );
  }

  // 新增理论内容
  static Future<void> insertTheory(Map<String, dynamic> data) async {
    final db = await database;
    await db.insert('theory', data, conflictAlgorithm: ConflictAlgorithm.replace);
  }

  // 更新理论内容
  static Future<void> updateTheory(Map<String, dynamic> data) async {
    final db = await database;
    await db.update('theory', data, where: 'id = ?', whereArgs: [data['id']]);
  }

  // 删除理论内容
  static Future<void> deleteTheory(String id) async {
    final db = await database;
    await db.delete('theory', where: 'id = ?', whereArgs: [id]);
  }

  // 查询所有理论内容
  static Future<List<Map<String, dynamic>>> getAllTheory() async {
    final db = await database;
    return await db.query('theory');
  }

  // 查询所有处方内容
  static Future<List<Map<String, dynamic>>> getAllPrescription() async {
    final db = await database;
    return await db.query('prescription');
  }
} 